// ==UserScript==
// @name         TapTap已知变灰
// @namespace    https://gitee.com/bluesword12350/web-script
// @version      1.0.0
// @author       李林峰
// @description  TapTap已知变灰
// @match        https://www.taptap.cn/upcoming
// @match        https://www.taptap.cn/app/*
// @icon
// @updateURL    https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-taptap.js
// @downloadURL  https://gitee.com/bluesword12350/web-script/raw/master/tampermonkey/sword-taptap.js
// @grant        GM_getValue
// @grant        GM_setValue
// ==/UserScript==

(() => {
  'use strict';
  const maxGames = 1000;
  const gameURLPattern = new URLPattern("https://www.taptap.cn/app/:gameId");
  const upcomingURL = "https://www.taptap.cn/upcoming";
  const GmGameKey = "已知游戏";
  let readGameIds = GM_getValue(GmGameKey, []);
  let knowItems = [];
  exec();
  function exec(){
    if (window.location.href === upcomingURL) {
      window.addEventListener("load", observe)
    }
    {
      let gameURLPatternResult = gameURLPattern.exec(window.location.href)
      if (gameURLPatternResult) {
        saveReadGameId(gameURLPatternResult.pathname.groups.gameId)
      }
    }
  }
  function saveReadGameId(gameId){
    let nowReadGameIds = GM_getValue(GmGameKey, []);
    if (!(nowReadGameIds instanceof Array)) {
      GM_setValue(GmGameKey, []);
    }
    if (!nowReadGameIds.includes(gameId)) {
      nowReadGameIds.unshift(gameId)
      GM_setValue(GmGameKey, nowReadGameIds);
    }
    while (nowReadGameIds.length > maxGames) {
      nowReadGameIds.pop()
    }
    readGameIds = nowReadGameIds;
  }
  function observe(){
    new MutationObserver(construction).observe(
        document.getElementsByClassName("tap-list")[0],
        {attributes: true, childList: true, subtree: true}
    );
  }
  function construction() {
    let upcomingItems = document.getElementsByClassName('upcoming-item');
    for (let upcomingItem of upcomingItems) {
      if (knowItems.includes(upcomingItem)) {
        continue
      }
      let gameURLPatternResult = gameURLPattern.exec(upcomingItem.getElementsByTagName('a')[0].href)
      if (gameURLPatternResult) {
        let gameId = gameURLPatternResult.pathname.groups.gameId
        if (readGameIds.includes(gameId)){
          upcomingItem.style.opacity = '0.3'
          knowItems.push(upcomingItem)
        } else if (!upcomingItem.classList.contains('upcoming-item--small')) {
          let button = document.createElement('button')
          button.innerText = '已知'
          button.classList.add('upcoming-item__app-button', 'tap-button', 'tap-button--small', 'tap-button--secondary', 'tap-button--wide-screen', 'tap-button--pc')
          button.onclick = () => {
            saveReadGameId(gameId)
          }
          upcomingItem.getElementsByClassName("upcoming-item__aside")[0].appendChild(button)
          knowItems.push(upcomingItem)
        }
      }
    }
  }
})();
